import json
import re
import logging

import requests.compat
from django.views import View
from apps.users.models import User
from utils.carts import merge_cart_cookie_to_redis
from django.http import JsonResponse
from meiduo_mall import settings

logger = logging.getLogger('django')


class UsernameCountView(View):
    def get(self, request, username):
        # if not re.match('[a-zA-z0-9_-]{5,20}', username):
        #     return JsonResponse({'code': 200, 'errmsg': '用户名不符合要求'})
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})


class MobileCountView(View):
    def get(self, request, mobile):
        # if not re.match('1[3-9]\d{9}', mobile):
        #     return JsonResponse({'code': 200, 'errmsg': '手机号不符合要求'})
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'count': count})


class RegisterView(View):
    def post(self, request):
        # 1.接收请求
        body_bytes = request.body
        body_str = body_bytes.decode()
        body_dict = json.loads(body_str)

        # 2.获取数据
        username = body_dict.get('username')
        password = body_dict.get('password')
        password2 = body_dict.get('password2')
        mobile = body_dict.get('mobile')
        allow = body_dict.get('allow')
        sms_code_client = body_dict.get('sms_code')

        # 3.验证数据
        if not all([username, password, password2, mobile, allow]):
            return JsonResponse({'code': 400, 'errmsg': '部分参数缺失'})
        if not re.match('[a-zA-Z0-9_-]{5,20}', username):
            return JsonResponse({'code': 400, 'errmsg': '用户名不符合要求'})
        if not re.match('1[3-9]\d{9}', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号不符合要求'})
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': '两次输入的密码不相同'})
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': '未确认用户协议'})

        # 验证短信验证码
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        sms_code_server = redis_cli.get(mobile)
        # 判断验证码是否过期
        if not sms_code_server:
            return JsonResponse({'code': 400, 'errmsg': '短信验证码已过期'})
        # 对比短信验证码与服务端储存的是否相同
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '短信验证码有误'})

        # 4.数据入库（密码未加密）
        # user=User(username=username, password=password, mobile=mobile)
        # user.save()
        # User.objects.create(username=username, password=password, mobile=mobile)

        # 4.数据入库（密码加密）
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '注册失败'})

        # 设置session信息
        # request.session['user_id']=user.id

        # django提供的状态保持的方法
        from django.contrib.auth import login
        # user是已登录的用户信息
        login(request, user)
        return JsonResponse({"code": 0, "errmsg": '注册成功'})


class LoginView(View):
    def post(self, request):
        # 获取信息
        data = json.loads(request.body)
        username = data.get('username')
        password = data.get('password')
        remembered = data.get('remembered')
        # 检验信息
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})

        # 判断是手机号登录还是用户名登录
        # 通过改变USERNAME_FIELD选择查询方式
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            User.USERNAME_FIELD = 'username'

        # 检验用户名与密码是否正确
        from django.contrib.auth import authenticate
        # authenticate参数为用户和密码，若用户密码正确，返回User信息，否则返回None
        user = authenticate(username=username, password=password)
        if user is None:
            return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})

        # session
        from django.contrib.auth import login
        login(request, user)

        # 判断是否记住登录
        if remembered is not None:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', username)
        response = merge_cart_cookie_to_redis(request, user, response)
        return response


from django.contrib.auth import logout


class LogoutView(View):
    def delete(self, request):
        # 删除session信息
        logout(request)
        # 删除cookie信息
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.delete_cookie('username')
        return response


# from django.contrib.auth.mixins import AccessMixin, LoginRequiredMixin
# class LoginRequiredJSONMixin(AccessMixin):
#     """Verify that the current user is authenticated."""
#
#     def dispatch(self, request, *args, **kwargs):
#         if not request.user.is_authenticated:
#             return JsonResponse({'code': 400, 'errmsg': '没有登陆'})
#         return super().dispatch(request, *args, **kwargs)
#
#
# class LoginRequiredJSONMixin(LoginRequiredMixin):
#     def handle_no_permission(self):
#         return JsonResponse({'code': 400, 'errmsg': '没有登陆'})


from utils.views import LoginRequiredJSONMixin


class CenterView(LoginRequiredJSONMixin, View):
    def get(self, request):
        info_data = {
            'username': request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_activate': request.user.email_active,
        }
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'info_data': info_data})


class EmailView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 1.接收数据
        data = json.loads(request.body)
        email = data.get('email')
        # 验证数据
        if not email:
            return JsonResponse({'code': 400, 'errmsg': '缺少email参数'})
        if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        # 2.保存邮箱地址
        user = request.user
        user.email = email
        user.save()
        # 3.发送邮件
        from django.core.mail import send_mail
        # subject,message,from_email,recipient_list,
        subject = '美多商城邮件'
        message = ""
        from_email = '美多商城<shen_dun_xi@163.com>'
        recipient_list = ['3209996299@qq.com']

        from apps.users.utils import generic_email_verify_token
        token = generic_email_verify_token(request.user.id)
        verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
        html_message = '<p>尊敬的用户您好！</p>' \
                       '<p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)
        from celery_tasks.email.tasks import celery_send_email
        celery_send_email.delay(subject, message, from_email, recipient_list, html_message)

        # 4.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


class EmailVerifyView(View):

    def put(self, request):
        # 1.获取数据
        params = request.GET
        token = params.get('token')
        # 2.验证参数
        if token is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 3.获取user_id
        from apps.users.utils import check_verify_token
        user_id = check_verify_token(token)
        if user_id is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 4.根据用户id查询数据
        user = User.objects.get(id=user_id)
        # 5.修改数据
        user.email_active = True
        user.save()
        # 6.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


from apps.users.models import Address


class AddressCreateView(LoginRequiredJSONMixin, View):
    def post(self, request):
        # 实现新增地址逻辑
        # 判断是否超过地址上限：最多20个
        # Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= 20:
            return JsonResponse({'code': 400, 'errmsg': '超过地址数量上限'})
        # 1.接收数据
        data = json.loads(request.body)
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        user = request.user

        # 2.验证数据（省略）
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': '缺少必要参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 400, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400, 'errmsg': '参数email有误'})
        # 3.数据入库
        address = Address.objects.create(
            user=user,
            title=receiver,
            receiver=receiver,
            province_id=province_id,
            city_id=city_id,
            district_id=district_id,
            place=place,
            mobile=mobile,
            tel=tel,
            email=email
        )

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        # 4.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'address': address_dict})


class AddressView(LoginRequiredJSONMixin, View):
    def get(self, request):
        # 1.查询数据
        user = request.user
        # addresses = user.addresses
        addresses = Address.objects.filter(user=user, is_deleted=False)
        # 2.将对象数据转换为字典数据
        address_list = []
        for address in addresses:
            address_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 3.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_list})


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):

    def put(self, request, address_id):
        # 1.接收数据
        json_dict = json.loads(request.body)
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2.验证数据
        # 省略

        # 3. 判断数据是否存在，并进行更新
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '更新数据失败'})

        # 4.返回响应
        address = Address.objects.get(id=address_id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        return JsonResponse({'code': 0, 'errmsg': '地址更新成功', 'address': address_dict})

    def delete(self, request, address_id):
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=address_id)
            # 逻辑删除
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


class DefaultAddressView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})
        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    def put(self, request, address_id):
        json_dict = json.loads(request.body)
        title = json_dict.get('title')
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': 400, 'errmsg': '修改标题错误'})
        return JsonResponse({'code': 0, 'errmsg': '修改标题成功'})


class ChangePasswordView(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 接收参数
        json_dict = json.loads(request.body)
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')

        # 校验数据（省略）

        # 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '修改密码失败'})
        # 清理状态保持信息
        logout(request)
        response = JsonResponse({'code': 0, 'errmsg': '修改密码成功'})
        response.delete_cookie('username')
        return response
